<template>
  <div class="notice_detail">
    <!-- 标题 -->
    <div class="input-field">
      <span>标&emsp;&emsp;题：</span>
      <input v-model="fromparam.n_title" type="text" />
    </div>
    <!-- 发件人 -->
    <div class="input-field">
      <span>发&ensp;件&ensp;人：</span>
      <input v-model="userinfo.username" type="text" />
    </div>
    <!-- 收件人 -->
    <div class="repicent">
      <div class="input-field">
        <span>收&ensp;件&ensp;人： </span>
        <div class="input-wrapper" @click="focusInput">
        <tagInputComp :tagList="selectedEmails" @remove="removeEmail"></tagInputComp>
        <input
          v-model="repicentInp"
          ref="repicentInpRef"
          @focus="isVisibale = true; isFocus = true;"
          @keydown.enter.prevent="HandleaddEmail"
          @blur="onBlur"
          type="text"
        >
        </input>
      </div>
      </div>
      <div v-if="userList.length > 0 && isVisibale" id="input_content">
        <tableSearch
          :userList="userList"
          @upisHoverTable="HoverTable"
          @upSelectUser="selectUser"
          :repicentInpRef="repicentInpRef"
        ></tableSearch>
      </div>
    </div>
    <!-- 通知类型 -->
    <el-radio-group v-model="fromparam.notice_type">
      <el-radio value="important" size="large">重要通知</el-radio>
      <el-radio value="general" size="large">一般通知</el-radio>
    </el-radio-group>
    <!-- 内容 -->
    <el-input
      v-model="fromparam.n_content"
      class="textarea-field"
      :autosize="{ minRows: 8, maxRows: 8 }"
      type="textarea"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { NewNoticeParams } from "../../../types/common";
import {
  User,
  UserSearchOnlyIdAndEmail,
  UserLikeParams,
} from "../../../types/user";
import { getUserListByKeywordApi } from "../../../api/user";
import { useUserStore } from "../../../store";
import { ElMessage } from "element-plus";
import tableSearch from "../component/search_table.vue";
import tagInputComp from "../component/tagInput.vue";

let isVisibale = ref(false);
let isHoverTabel = ref(false);
let isFocus = ref(false);
let repicentInpRef = ref<HTMLInputElement>();
const store = useUserStore();
const selectedEmails = ref<string[]>(["ALL"]);
const emits = defineEmits<{
  (event: "update:modelValue", value: NewNoticeParams): void;
}>();

let repicentInp = ref<string>("");

let fromparam = ref<NewNoticeParams>({
  n_id: 0,
  sender_email: "",
  sender_username: "",
  sender_uid: 0,
  n_title: "",
  notice_type: "important",
  n_content: "",
  n_time: "",
  recipient: "all",
  recipientUIDs: [],
});
let userinfo = ref<User>(store.user);

let userList = ref<UserSearchOnlyIdAndEmail[]>([
  { id: 0, email: "", username: "" },
]);
const HoverTable = (value: boolean) => {
  isHoverTabel.value = value;
};
const selectUser = (user: UserSearchOnlyIdAndEmail) => {
  selectedEmails.value.push(user.email);
  fromparam.value.recipientUIDs.push(user.id);
  repicentInp.value = "";
};

function HandleaddEmail() {
    if (repicentInp.value.trim() && !selectedEmails.value.includes(repicentInp.value.trim())) {
      selectedEmails.value.push(repicentInp.value.trim());
      repicentInp.value = ''; // 清空输入框
    }
}
function removeEmail(index: number) {
  selectedEmails.value.splice(index, 1);
}
function focusInput() {
  const inputElement = repicentInpRef.value as HTMLInputElement;
  inputElement.focus();
}
function onBlur() {
  isFocus.value = false;
  isVisibale.value = isHoverTabel.value ? isHoverTabel.value : isHoverTabel.value;
}
// 获取发送人自己的消息
onMounted(() => {
  fromparam.value.sender_email = userinfo.value.email;
  fromparam.value.sender_username = userinfo.value.username;
  // 将string 转化成 数字
  fromparam.value.sender_uid = Number(userinfo.value.id);
  emits("update:modelValue", fromparam.value);
});
// 抛出fromparam数据f
var timer: NodeJS.Timeout;

// 请求搜索的用户列表
async function searchUser() {
  let params: UserLikeParams = {
    page: 1,
    limit: 10,
    filed: repicentInp.value,
  };
  try {
    const respnose = await getUserListByKeywordApi(params);
    if (respnose.code == 200) {
      userList.value = respnose.result.list;
    }
  } catch (error) {
    ElMessage({
      message: "请求失败",
      type: "error",
    });
  }
}

watch(
  repicentInp,
  (value) => {
    if (value == "") {
      userList.value = [];
    }
    if (!value) return;
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      searchUser();
      isVisibale.value = true;
    }, 500);
  },
  { immediate: true }
);
watch(
  isHoverTabel,
  (value) => {
    if (value == false && isFocus.value == false && isVisibale.value == true) {
      isVisibale.value = false;
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.notice_detail {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  max-width: 600px;
  margin: 0 auto;
  .input-field {
    display: flex;
    align-items: center;
    height: 32px;
    margin-bottom: 10px;
    border-radius: 10px;
    span {
      display: flex;
      align-items: center;
      background-color: #f5f7fa;
      padding: 5px;
      height: 100%;
      min-width: 80px;
      max-width: max-content;
      border: 1px solid #ccc;
      border-right: 0px;
      color: #9093a5;
      border-radius: 10px 0px 0px 10px;
    }
    input {
      height: 100%;
      border-style: none;
      padding-left: 10px;
      flex: 1;
      border: 1px solid #cdd0d6;
      &:focus {
        outline: none;
        border: 1px solid #409eff;
        border-radius: 0px 10px 10px 0px;
      }
    }
  }
  .input-wrapper {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  border: 1px solid #ccc;
  padding: 5px;
}
  .repicent {
    position: relative;
    #input_content {
      position: absolute;
      width: 100%;
      z-index: 1;
      border: 1px solid #ccc;
      background-color: #ccc;
      display: block;
    }
  }

  .textarea-field {
    border: 1px solid #ccc;
    padding: 5px;
    resize: none;
  }
}
</style>
